import * as api from '@/api/study';

const state = {
  progress: null,
  records: []
};

const mutations = {
  SET_PROGRESS(state, progress) {
    state.progress = progress;
  },
  SET_RECORDS(state, records) {
    state.records = records;
  }
};

const actions = {
  // 获取学习进度
  getStudyProgress({ commit }) {
    return new Promise((resolve, reject) => {
      api.getStudyProgress()
        .then(res => {
          commit('SET_PROGRESS', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 获取学习记录
  getStudyRecords({ commit }) {
    return new Promise((resolve, reject) => {
      api.getStudyRecords()
        .then(res => {
          commit('SET_RECORDS', res.data);
          resolve(res.data);
        })
        .catch(err => {
          reject(err);
        });
    });
  },

  // 提交学习记录
  submitStudyRecord({ commit }, recordData) {
    return new Promise((resolve, reject) => {
      api.submitStudyRecord(recordData)
        .then(res => {
          // 更新学习记录
          return api.getStudyRecords().then(recordsRes => {
            commit('SET_RECORDS', recordsRes.data);
            // 更新学习进度
            return api.getStudyProgress().then(progressRes => {
              commit('SET_PROGRESS', progressRes.data);
              resolve(res);
            });
          });
        })
        .catch(err => {
          reject(err);
        });
    });
  }
};

const getters = {
  progress: state => state.progress,
  records: state => state.records,
  totalProgress: state => state.progress ? state.progress.total_progress : 0,
  subjectProgress: state => {
    if (!state.progress) return {};
    
    return {
      subject1: {
        type: 'subject1',
        status: state.progress.subject1_status,
        hours: state.progress.subject1_hours
      },
      subject2: {
        type: 'subject2',
        status: state.progress.subject2_status,
        hours: state.progress.subject2_hours
      },
      subject3: {
        type: 'subject3',
        status: state.progress.subject3_status,
        hours: state.progress.subject3_hours
      },
      subject4: {
        type: 'subject4',
        status: state.progress.subject4_status,
        hours: state.progress.subject4_hours
      }
    };
  }
};

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
};